import { reqCartList, reqDeleteCartById, reqCheckCart } from "@/api";


const state = {
    cartData: []
};
const mutations = {
    GETCARTLIST(state, cartData) {
        state.cartData = cartData
    }
}
const actions = {
    //获取购物车列表数据
    async getCartList({ commit }) {
        let result = await reqCartList();//返回购物车列表
        if (result.code === 200) {
            commit('GETCARTLIST', result.data)
        }

    },
    //删除购物车某一个产品
    async reqDeleteCartById({ commit }, skuId) {
        let result = await reqDeleteCartById(skuId);
        if (result.code === 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    //修改商品是否选中状态
    async reqCheckCart({ commit }, { skuId, isChecked }) {
        let result = await reqCheckCart(skuId, isChecked);
        if (result.code == 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'));
        }
    },
    //删除全部勾选的商品
    deleteAllCheckedById({ dispatch, getters }) {
        //获取全部的产品
        let PromiseAll = []
        getters.cartList.cartInfoList.forEach(item => {
            let promise = item.isChecked == 1 ? dispatch('reqDeleteCartById', item.skuId) : '';
            PromiseAll.push(promise)
        })

        return Promise.all(PromiseAll)
    },
    //修改全部商品选中状态
    updataAllCartIsChecked({ dispatch, getters }, isChecked) {
        let promiseAll = []
        //遍历全部的isChecked状态
        getters.cartList.cartInfoList.forEach((item) => {
            let promise = dispatch('reqCheckCart', {
                skuId: item.skuId,
                isChecked
            })
            promiseAll.push(promise)
        })
        return Promise.all(promiseAll)
    }

}
const getters = {
    cartList(state) {
        return state.cartData[0] || {}
    }
}

export default {
    state, mutations, actions, getters
}